﻿namespace Pibby.Core
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    using Pibby.Core.IO;

	public class Downloadable : Identifiable, IDownloadable
	{
		#region Attributes
		private Uri _link;

		#endregion Attributes

		#region Constructor

		public Downloadable()
		{
		}

		public Downloadable(Uri link)
			: this(link, string.Empty)
		{
		}

		public Downloadable(Uri link, string folder)
		{
			this.Uri = link;
			this.TargetFolder = folder;
		}

		#endregion

		#region Methods

		public override string ToString()
		{
			if (string.IsNullOrEmpty(this.FriendlyName))
			{
				return this.Uri.AbsoluteUri;
			}

			return string.Format(System.Globalization.CultureInfo.CurrentUICulture, "{0} : {1}", this.FriendlyName, this.Uri.AbsoluteUri);
		}

		#endregion

		#region Properties

		public Uri Uri
		{
			get { return this._link; }
			set
			{
				this._link = value;

				if (value != null)
				{
					this.FileName = FileNameSanitizer.FixWebLink(System.IO.Path.GetFileName(value.AbsoluteUri));

					if (string.IsNullOrEmpty(this.FileName))
					{
						this.FileName = "rss.xml";
					}

					this.FriendlyName = this.FileName;
				}
			}
		}

		public string TargetFolder
		{
			get;
			set;
		}

		public string LocalPath
		{
			get 
			{
				Contract.EnsureIsNotNullOrEmpty(this.TargetFolder, "TargetFolder is blank");
				Contract.EnsureIsNotNullOrEmpty(this.SafeFileName, "SafeFileName is blank");

				return System.IO.Path.Combine(this.TargetFolder, this.SafeFileName); 
			}
		}

		public string FileName
		{
			get;
			set;
		}

		public string FriendlyName
		{
			get;
			set;
		}

		private string SafeFileName
		{
			get
			{
				return FileNameSanitizer.FixWebLink(this.FileName);
			}
		}

		public long FileSize
		{
			get;
			set;
		}

		// whether to save to file or in memory
		public bool InMemoryDownload
		{
			get;
			set;
		}

		// if no target folder is set - will download into content.
		public string Content
		{
			get;
			set;
		}

		public object Tag
		{
			get;
			set;
		}

		#endregion
	}
}
